package com.powerunion.datacollection.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.SubFormDataDao;
import com.powerunion.datacollection.model.ApproveWorkItem;
import com.powerunion.datacollection.model.MaintblData;
import com.powerunion.datacollection.model.SubmissionWorkItem;
import com.powerunion.datacollection.model.jsonObject.DBTableField;
import com.powerunion.datacollection.model.jsonObject.JSONDataBean;

import com.powerunion.util.log.LogHelper;

public class SubFormDataManager {
	private static Logger logger = LogHelper.getInstance().getLogger(
			SubFormDataManager.class);
	private SubFormDataDao dao = null;

	public SubFormDataManager() {
		super();
		this.dao = (SubFormDataDao) DaoFactory.getInstance().getDao(
				SubFormDataDao.class);
	}

	public boolean save4MainTbl(MaintblData data, String formValues)
			throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(formValues)) {
			String[] args = { "formValues" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter formValues NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		// 参数为空
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.save4MainTbl(data, formValues);
	}

	public boolean save4SubTbl(MaintblData data, String formValues)
			throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(formValues)) {
			String[] args = { "formValues" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter formValues NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		// 参数为空
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		Map objectMap = new HashMap();
		objectMap.put("data", JSONObject.class);
		JSONDataBean cl = (JSONDataBean)JSONObject.toBean(JSONObject.fromObject(formValues), JSONDataBean.class,objectMap);
		return this.dao.save4SubTbl(data, cl.getData());
	}

	public String getMaintblDataInfo4SubFormMaintTbl(MaintblData data,int requestType)
			throws Exception {
		// 参数为空
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		JSONObject jsonObject = this.dao
				.getMaintblDataInfo4SubFormMaintTbl(data,requestType);
		String info = "{success:true,data:[" + jsonObject + "]}";

		return info;
	}
	
	public String getSubFormData(MaintblData data,int requestType) throws Exception {
		// 参数为空
		if (data == null) {
			String[] args = { "data" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		List datas = this.dao.getSubFormData(data,requestType);
		JSONArray jsonArray = JSONArray.fromObject(datas);
		String result = "{results:"+jsonArray+"}";
		return result;
	}
	
	public String getAllMaintblDatasByAct(String procId, String actId,
			int currentOrparrent) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter data NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		ApproveWorkItemManager awm = new ApproveWorkItemManager();
		ApproveWorkItem awi = awm.getByKey(actId);
		SubmissionWorkItemManager swm = new SubmissionWorkItemManager();
		List submissionWorkItems = new ArrayList();
		if (currentOrparrent == Constants.DATACOLLECTVIEW_REQUEST_TYPE_SUBMIDATA) {// 请求的是当前上报的任务数据
			// 得到当前上报的步骤类型
			int preActType = awi.getPreActType();
			String preActId = awi.getPreActId();

			// 当前上报的是采集步骤
			if (preActType == Constants.COLLECTION_STEP_TYPE) {
				submissionWorkItems = swm.getAllSubWorksByAct(procId, preActId,
						1);
			} else if (currentOrparrent == Constants.APPROVE_STEP_TYPE) {
				submissionWorkItems = swm.getAllSubWorksByAct(procId, preActId,
						2);
			}

		} else if (currentOrparrent == Constants.DATACOLLECTVIEW_REQUEST_TYPE_COLLECT) {// 请求的是汇总所有上报数据
			submissionWorkItems = swm.getAllSubWorksByAct(procId, actId, 2);
		}
		if (submissionWorkItems.size() < 1) {
			return "{results:''}";
		} else {
			SubmissionWorkItem swi = (SubmissionWorkItem) submissionWorkItems
					.get(0);
			MaintblDataManager mdm = new MaintblDataManager();
			List fields = mdm.getMaintblFields(swi.getFormId());
			String result = "";
			if (fields.isEmpty()) {
				return result = "{results:''}";
			}

			List maintblDatas = mdm
					.getAllMaintblDataByAct4subTbl(submissionWorkItems);

			List allMaintblDatas = new ArrayList();
			// 重组数据
			for (int i = 0; i < fields.size(); i++) {
				DBTableField df = (DBTableField) fields.get(i);
				JSONObject record = new JSONObject();
				// 主表字段名为第一列
				record.put("column0", df.getFieldLabel());
				// 遍历主表数据 依次取出同个主表字段对应的值
				for (int j = 0; j < maintblDatas.size(); j++) {
					JSONObject jo = (JSONObject) maintblDatas.get(j);
					int index = j + 1;
					record.put("column" + index, jo.get(df.getFieldName()));
				}
				allMaintblDatas.add(record);
			}

			JSONArray jsonArr = JSONArray.fromObject(allMaintblDatas);
			result = "{results:" + jsonArr + "}";
			return result;
		}

	}
	
	public String getSubFormData4Approve(String procId,List submissionWorkItems,int requestType) throws DaoException{
		// 参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (submissionWorkItems == null) {
			String[] args = { "submissionWorkItems" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter submissionWorkItems NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		List datas = this.dao.getSubFormData4Approve(procId, submissionWorkItems, requestType);
		JSONArray jsonArray = JSONArray.fromObject(datas);
		String result = "{results:"+jsonArray+"}";
		return result;
	}

}
